
<template>
  <view class="designer-list-page">
    <!-- 筛选区域 - 放在一行 -->
    <view class="filter-section">
      <view class="filter-row">
        <picker @change="onHouseTypeChange" range-key="dictValue" :range="houseTypes">
          <view class="picker-item">
            {{ houseType ? houseType.dictValue : '选择户型' }}
          </view>
        </picker>
        <picker @change="onHouseAreaChange" range-key="dictValue" :range="houseAreas">
          <view class="picker-item">
            {{ houseArea ? houseArea.dictValue : '选择面积' }}
          </view>
        </picker>
        <picker @change="onHouseStyleChange" range-key="dictValue" :range="houseStyles">
          <view class="picker-item">
            {{ houseStyle ? houseStyle.dictValue : '选择风格' }}
          </view>
        </picker>
        <picker @change="onHouseBudgetChange" range-key="dictValue" :range="houseBudgets">
          <view class="picker-item">
            {{ houseBudget ? houseBudget.dictValue : '选择预算' }}
          </view>
        </picker>
      </view>
    </view>

    <!-- 案例列表 -->
    <scroll-view class="designer-list" scroll-y refresher-enabled :refresher-triggered="isRefreshing"
                 @refresherrefresh="onRefresh" @scrolltolower="onLoadMore" @scroll="onScroll" :scroll-top="scrollTop"
                 :scroll-with-animation="true" :scroll-anchoring="true" :bounces="false">
      <view v-for="(item, index) in caseList" :key="index" class="designer-item">
        <!-- 头部信息 -->
        <view class="case-header" @tap="toDetail(item.sbId)">
          <image :src="getFullImageUrl(getFirstImage(item.sbImages))" class="case-image" mode="aspectFill"></image>
          <view class="case-info">
            <view class="case-title">{{ item.sbTitle }}</view>
            <view class="case-details">
              <text class="detail-item">户型: {{ getDictLabel(houseTypes, item.houseType) }}</text>
              <text class="detail-item">面积: {{ getDictLabel(houseAreas, item.houseArea) }}</text>
              <text class="detail-item">预算: {{ getDictLabel(houseBudgets, item.houseBudget) }}</text>
            </view>
          </view>
        </view>

        <!-- 风格标签 -->
        <view class="styles-section">
          <view class="style-tag">
            {{ getDictLabel(houseStyles, item.houseStyle) }}
          </view>
        </view>
      </view>
      <!-- 加载状态 -->
      <view class="loading" v-if="isLoading">加载中...</view>
      <view class="no-more" v-if="noMore">没有更多数据了</view>
    </scroll-view>

    <!-- 返回顶部按钮 -->
    <view class="back-to-top" :class="{ show: showBackTop }" @tap="backToTop">
      <text class="top-text">⬆</text>
    </view>

    <!-- 全屏图片画廊弹窗 -->
    <view v-if="showGallery" class="gallery-overlay" @tap="closeGallery">
      <view class="gallery-container" @tap.stop.prevent>
        <!-- 全屏图片容器 -->
        <view class="gallery-fullscreen"
              @touchstart="handleTouchStart"
              @touchmove="handleTouchMove"
              @touchend="handleTouchEnd">
          <image
              :src="currentImage"
              class="gallery-image"
              :style="imageStyle"
              mode="aspectFit"
              @tap.stop.prevent="handleImageTap"
          ></image>
        </view>

        <!-- 顶部信息栏 -->
        <view class="gallery-header">
          <text class="gallery-index">{{ currentImageIndex + 1 }}/{{ worksList.length }}</text>
          <view class="gallery-actions">
            <text class="gallery-action" @tap="resetTransform">重置</text>
            <text class="gallery-close" @tap="closeGallery">✕</text>
          </view>
        </view>

        <!-- 底部指示器 -->
        <view class="gallery-footer">
          <view class="gallery-dots">
            <view
                v-for="(image, index) in worksList"
                :key="index"
                class="gallery-dot"
                :class="{ active: currentImageIndex === index }"
                @tap="switchImage(index)"
            ></view>
          </view>
        </view>

        <!-- 左右切换箭头 -->
        <view v-if="worksList.length > 1" class="gallery-arrows">
          <text class="gallery-arrow gallery-arrow-left" @tap="prevImage" :class="{ disabled: currentImageIndex === 0 }">‹</text>
          <text class="gallery-arrow gallery-arrow-right" @tap="nextImage" :class="{ disabled: currentImageIndex === worksList.length - 1 }">›</text>
        </view>
      </view>
    </view>
  </view>
</template>

<style scoped lang="scss">.designer-list-page {
  background-color: #f8f9fa;
  height: 100vh;
}

.filter-section {
  background-color: #fff;
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.filter-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 20rpx;
  flex-wrap: wrap;
}

.filter-label{
  font-size: 24rpx;
  color: #000;
}

.picker-item {
  font-size: 24rpx;
  color: #666;
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
  background-color: #f5f5f5;
  text-align: center;
}

.designer-list {
  height: calc(100vh - 200rpx);
}

.designer-item {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}

.case-header {
  position: relative;
  height: 300rpx;
  overflow: hidden;
}

.case-image {
  width: 100%;
  height: 100%;
}

.case-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
  padding: 20rpx;
  color: #ffffff;
}

.case-title {
  font-size: 30rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.case-details {
  display: flex;
  justify-content: space-between;
}

.detail-item {
  font-size: 24rpx;
  background-color: rgba(255,255,255,0.2);
  padding: 4rpx 12rpx;
  border-radius: 8rpx;
  margin-right: 10rpx;
}

.styles-section {
  padding: 20rpx 30rpx;
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
}

.style-tag {
  font-size: 24rpx;
  color: #666;
  padding: 6rpx 12rpx;
  border-radius: 12rpx;
  background-color: #f5f5f5;
}

.loading, .no-more {
  text-align: center;
  padding: 20rpx;
  font-size: 28rpx;
  color: #999;
}

/* 返回顶部按钮样式 */
.back-to-top {
  position: fixed;
  right: 30rpx;
  bottom: 100rpx;
  width: 80rpx;
  height: 80rpx;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
  z-index: 999;
}

.back-to-top.show {
  opacity: 1;
}

.top-text {
  color: white;
  font-size: 32rpx;
}
</style>

<script>import {fetchPaginatedDataNoLogin} from "../../utils/http";

export default {
  name: "case",
  data() {
    return {
      //户型 SHOW_HOUSE_TYPE
      houseType: null,
      houseTypes: [],
      selectedHouseType: '', // Add this to track selected value

      //面积 HOUSE_AREA
      houseArea: null,
      houseAreas: [],
      selectedHouseArea: '', // Add this to track selected value

      //风格 HOUSE_STYLE
      houseStyle: null,
      houseStyles: [],
      selectedHouseStyle: '', // Add this to track selected value

      //预算 HOUSE_BUDGET
      houseBudget: null,
      houseBudgets: [],
      selectedHouseBudget: '', // Add this to track selected value


      currentTab: 0,
      caseList: [],
      page: 1,
      pageSize: 10,
      isLoading: false,
      noMore: false,
      showBackTop: false,
      isRefreshing: false,
      scrollTop: 0,
      oldScrollTop: 0,

      // 图片画廊相关数据
      showGallery: false,
      currentImageIndex: 0,
      worksList: [],
      scale: 1,
      lastScale: 1,
      translateX: 0,
      translateY: 0,
      lastTranslateX: 0,
      lastTranslateY: 0,
      startX: 0,
      startY: 0,
      isDragging: false,
      isScaling: false,
      initialDistance: 0,
      lastTouchTime: 0
    };
  },
  onLoad() {
    this.loadData();
  },
  methods: {
    //房屋类型
    loadHouseType() {
      var that = this;
      this.$shopxHttp.httpRequestNoLogin({
        url: '/sysDict/selectListByCode',
        submitType: 'POST',
        data: {dictCode:'SHOW_HOUSE_TYPE'},
        successCallback: (res) => {
          // Prepend "all" option to the beginning of the array
          that.houseTypes = [{dictName: '', dictValue: '全部户型'}, ...res.rspData];
        },
        isSucAlert: 'y'
      });
    },
    //面积
    loadHouseArea() {
      var that = this;
      this.$shopxHttp.httpRequestNoLogin({
        url: '/sysDict/selectListByCode',
        submitType: 'POST',
        data: {dictCode:'HOUSE_AREA'},
        successCallback: (res) => {
          // Prepend "all" option to the beginning of the array
          that.houseAreas = [{dictName: '', dictValue: '全部面积'}, ...res.rspData];
        },
        isSucAlert: 'y'
      });
    },

//风格
    loadHouseStyle() {
      var that = this;
      this.$shopxHttp.httpRequestNoLogin({
        url: '/sysDict/selectListByCode',
        submitType: 'POST',
        data: {dictCode:'HOUSE_STYLE'},
        successCallback: (res) => {
          // Prepend "all" option to the beginning of the array
          that.houseStyles = [{dictName: '', dictValue: '全部风格'}, ...res.rspData];
        },
        isSucAlert: 'y'
      });
    },

//预算
    loadHouseBudget() {
      var that = this;
      this.$shopxHttp.httpRequestNoLogin({
        url: '/sysDict/selectListByCode',
        submitType: 'POST',
        data: {dictCode:'HOUSE_BUDGET'},
        successCallback: (res) => {
          // Prepend "all" option to the beginning of the array
          that.houseBudgets = [{dictName: '', dictValue: '全部预算'}, ...res.rspData];
        },
        isSucAlert: 'y'
      });
    },

    async loadData() {
      if (this.isLoading) return;

      this.isLoading = true;
      const pageStart = (this.page - 1) * this.pageSize;
      const model = {
        isPage: '1',
        pageStart: pageStart,
        pageLength: this.pageSize,
        houseType: this.selectedHouseType,     // 户型筛选条件
        houseArea: this.selectedHouseArea,     // 面积筛选条件
        houseStyle: this.selectedHouseStyle,   // 风格筛选条件
        houseBudget: this.selectedHouseBudget  // 预算筛选条件
      };

      try {
        const res = await fetchPaginatedDataNoLogin('/showBasicCase/queryPageList', model, this.page, this.pageSize);
        const data = res.data;

        // 确保 data 是一个数组
        if (Array.isArray(data)) {
          if (this.page === 1) {
            this.caseList = data; // 如果是第一页，直接赋值
          } else {
            this.caseList = this.caseList.concat(data); // 追加数据
          }
          this.noMore = data.length < this.pageSize; // 判断是否还有更多数据
        } else {
          uni.showToast({
            title: '数据格式错误',
            icon: 'none'
          });
        }
      } catch (error) {
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
      } finally {
        this.isLoading = false;
        this.isRefreshing = false;
      }
    },

    // 获取完整图片URL
    getFullImageUrl(imagePath) {
      if (!imagePath) return '/static/default-image.png'; // 默认图片
      return this.$ossPath + imagePath;
    },

    // 获取第一张图片
    getFirstImage(imagesString) {
      if (!imagesString) return '';
      const images = imagesString.split(',');
      return images[0] || '';
    },

    // 获取字典标签
    getDictLabel(dictList, dictKey) {
      if (!dictKey || !Array.isArray(dictList)) return '未设置';
      const dictItem = dictList.find(item => item.dictName === dictKey);
      return dictItem ? dictItem.dictValue : '未知';
    },

    // 修改返回顶部方法
    backToTop() {
      this.scrollTop = this.oldScrollTop;
      this.$nextTick(() => {
        this.scrollTop = 0;
      });
    },

    // 滚动监听方法
    onScroll(e) {
      const scrollTop = e.detail.scrollTop;
      this.showBackTop = scrollTop > 500;
      this.oldScrollTop = scrollTop;
    },

    // 修改下拉刷新处理
    async onRefresh() {
      if (this.isLoading) return;

      this.isRefreshing = true; // 设置刷新状态
      this.page = 1;
      this.noMore = false;

      try {
        await this.loadData();
      } catch (error) {
        uni.showToast({
          title: '刷新失败',
          icon: 'none'
        });
      } finally {
        this.isRefreshing = false;
      }
    },

    // 触底加载更多
    onLoadMore() {
      if (!this.isLoading && !this.noMore && !this.isRefreshing) {
        this.page++;
        this.loadData();
      }
    },

    // 预约设计师
    // bookDesigner(id) {
    //   uni.navigateTo({
    //     url: `/pages/staff/designer_contract?id=${id}`
    //   });
    // },

    // 查看详情
    toDetail(id) {
      uni.navigateTo({
        url: `/pages/case/detail?sbId=${id}`
      });
    },

    // 筛选器变更事件
    onHouseTypeChange(e) {
      this.houseType = this.houseTypes[e.detail.value];
      this.selectedHouseType = this.houseType ? this.houseType.dictName : '';
      this.performSearch(); // Trigger search after selection
    },

    onHouseAreaChange(e) {
      this.houseArea = this.houseAreas[e.detail.value];
      this.selectedHouseArea = this.houseArea ? this.houseArea.dictName : '';
      this.performSearch(); // Trigger search after selection
    },

    onHouseStyleChange(e) {
      this.houseStyle = this.houseStyles[e.detail.value];
      this.selectedHouseStyle = this.houseStyle ? this.houseStyle.dictName : '';
      this.performSearch(); // Trigger search after selection
    },

    onHouseBudgetChange(e) {
      this.houseBudget = this.houseBudgets[e.detail.value];
      this.selectedHouseBudget = this.houseBudget ? this.houseBudget.dictName : '';
      this.performSearch(); // Trigger search after selection
    },
    // 新增搜索方法
    performSearch() {
      this.page = 1; // Reset to first page
      this.loadData(); // Reload data with new filters
    },
  },
  computed: {
    currentImage() {
      return this.worksList[this.currentImageIndex]?.image || '';
    },
    imageStyle() {
      return {
        transform: `translate(${this.translateX}px, ${this.translateY}px) scale(${this.scale})`,
        transition: this.isDragging || this.isScaling ? 'none' : 'transform 0.2s ease'
      };
    }
  },
  mounted() {
    this.loadHouseType();
    this.loadHouseArea();
    this.loadHouseStyle();
    this.loadHouseBudget();
  },
}
</script>